{% extends './base.html' %}
{% block head %}
{% endblock %}
{% block content %}
<div class="m-3">
    <h1 class="display-1">注册账号</h1>
    <form class="m-2 signupform" action="{% url 'lesson:signup' %}" method="POST">
        {% csrf_token %}
        <div class="mb-3">
            <label class="form-label">用户名</label>
            <input name="username" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
                required>
        </div>
        <div class="mb-3">
            <label for="exampleInputPassword1" class="form-label">密码</label>
            <input name="password" type="password" class="form-control" id="exampleInputPassword1" required>
            <div id="passwordHelpBlock" class="form-text">你的密码会被加密存储，即使我们也不知道你的密码。
            </div>
        </div>
        <div class="mb-3">
            <label for="exampleInputPassword1" class="form-label">确认密码</label>
            <input name="confirm_password" type="password" class="form-control" id="exampleInputPassword1" required>
        </div>
        <div class="mb-3 form-check">
            <input name=agreed type="checkbox" class="form-check-input" id="exampleCheck1" required>
            <label class="form-check-label" for="exampleCheck1">我承诺以尊重他人的方式发表言论</label>
        </div>
        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
            <button type="submit" class="btn btn-primary">注册</button>
        </div>
    </form>
</div>
<script async>
    let signupform = document.querySelector('.signupform');

    function sendcomment(target) {
        let XHR = new XMLHttpRequest();
        let FD = new FormData(target);
        XHR.addEventListener('load', function (event) {
            obj = JSON.parse(event.target.responseText);
            if (obj['succeeded'] == true) {
                alert('注册成功！')
                window.location.href = '/';
            } else {
                alert(obj['message']);
            }
        });
        XHR.addEventListener('error', function (event) {
            alert("提交失败，请检查网络连接并重载本页面");
        });
        XHR.open('POST', '/signup/');
        XHR.send(FD);
    }

    signupform.addEventListener('submit', function (event) {
        event.preventDefault();
        sendcomment(event.target);
    });
</script>
{% endblock %}